<?php
/**
 * Created by PhpStorm
 * User: whh
 * Date: 2022/8/12
 * Time: 16:12
 */

namespace app\common\model;


use think\Db;
use think\Model;

class UserBookPoints extends Model
{
    const payment = 1;//支付购买
    const background_recharge = 2;//后台充值
    const add_desktop = 3;//加桌赠送
    const sign = 4;//签到赠送
    const binding = 5;//绑定号码
    const calendar = 6;//日历提醒
    const read = 7;//阅读X章节
    const pay_give = 8;//充值赠送

    protected $table = 'quick_user_book_points';
    use Common;

    /**
     * 送书点
     * @param $uid
     * @param $number
     * @param $giveType
     * @param int $continuousDays
     */
    public function givePoint($uid, $number, $giveType,$continuousDays = 1)
    {
        $save = [
            'uid' => $uid,
            'give_type' => $giveType,
            'book_point' => $number,
            'overdue_time' => time() + (86400 * 15),
            'date' => date("Y-m-d"),
            'continuous_days' => $continuousDays
        ];
        Db::table($this->table)->insert($save);
    }


    public function getOverdueDateAttr($value, $data)
    {
        return date("Y-m-d H:i:s", $data['overdue_time']);
    }

    /**
     * 获取书点余额
     * @param $uid
     * @return UserBookPoints|int
     * @Author: whh
     */
    public function getBalancePoint($uid)
    {
        $where[] = ['uid', '=', $uid];
        $where[] = ['is_expire', '=', 0];
        $where[] = ['overdue_time', '>', time()];
        $point = $this->where($where)->sum("book_point");
        $point = $point ?? 0;
        return $point;
    }

    /**
     * @param $uid
     * @param $useCount @消费点数
     * @return int 返回剩余需要消费的点数
     * @throws \think\Exception
     */
    public function usePoint($uid, $useCount)
    {
        if ($useCount > 0) {
            $where[] = ['uid', '=', $uid];
            $where[] = ['is_expire', '=', 0];
            $where[] = ['overdue_time', '>', time()];
            $where[] = ['book_point', '>', 0];
            $list = $this->where($where)->field("id,book_point")->order("overdue_time asc,id asc")->select();

            foreach ($list as $k => $v) {
                if ($useCount > 0) {
                    if ($v['book_point'] >= $useCount) {
                        $this->where("id", $v['id'])->setDec('book_point', $useCount);
                        $this->where("id", $v['id'])->setInc('used_point', $useCount);
                        $useCount = $useCount > $v['book_point'] ? $useCount - $v['book_point'] : 0;//使用书点 > 表内余额才需要减去，不然此表记录还有余额，不能减会变负数
                        break;
                    } else {
                        //分次消耗
                        $this->where("id", $v['id'])->setDec('book_point', $v['book_point']);
                        $this->where("id", $v['id'])->setInc('used_point', $v['book_point']);
                        $useCount = $useCount - $v['book_point'];
                    }
                }
            }
        }
        return $useCount;
    }
}